/**   
 * @Title: Util.java
 * @Package com.practices.util
 * @Description: TODO
 * @author woailuo 
 * @date 2013-4-21 下午12:10:00
 * @version V1.0   
 */
package com.practices2.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.practices2.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class Util {
	private static boolean debug = true;
	private static String TAG = "AndroidPractice";

	public static void log(Object obj) {
		Log.d(TAG, "**************" + obj.toString());
	}

	public static void log(String obj) {
		Log.d(TAG, "**************" + obj);
	}

	public static void showModeDialog(Context cx) {
		Dialog d = new Dialog(cx);
		Window window = d.getWindow();
		window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
		d.show();
	}

	/* 普通的对话框 ,有确定与取消 */
	public static void showNormalDia(Context cx, int iconid, String title, String message) {
		// AlertDialog.Builder normalDialog=new
		// AlertDialog.Builder(getApplicationContext());
		AlertDialog.Builder normalDia = new AlertDialog.Builder(cx);
		normalDia.setIcon(iconid);
		normalDia.setTitle(title);
		normalDia.setMessage(message);

		normalDia.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		normalDia.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		normalDia.create().show();
	}

	public static void showMultiDia(Context cx, String title) {
		AlertDialog.Builder multiDia = new AlertDialog.Builder(cx);
		multiDia.setTitle(title);
		multiDia.setPositiveButton("按钮一", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		multiDia.setNeutralButton("按钮二", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		multiDia.setNegativeButton("按钮三", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		multiDia.create().show();
	}

	/* 列表对话框 */
	public static void showListDia(Context cx, String title, String[] strList) {
		AlertDialog.Builder listDia = new AlertDialog.Builder(cx);
		listDia.setTitle(title);
		listDia.setItems(strList, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				/* 下标是从0开始的 */
			}
		});
		listDia.create().show();
	}

	/* 单项选择对话框 */
	public static int yourChose = -1;

	public static void showSinChosDia(Context cx, String title) {
		final String[] mList = { "选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项7" };
		yourChose = -1;
		AlertDialog.Builder sinChosDia = new AlertDialog.Builder(cx);
		sinChosDia.setTitle(title);
		sinChosDia.setSingleChoiceItems(mList, 0, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				yourChose = which;

			}
		});
		sinChosDia.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if (yourChose != -1) {

				}
			}
		});
		sinChosDia.create().show();
	}

	// 进度读取框需要模拟读取
	private static ProgressDialog progressDialog = null;
	public final static int MAX_READPROCESS = 100;

	public static void showProgressDialogstyleHorizontal(Context cx, String title) {

		progressDialog = new ProgressDialog(cx);
		progressDialog.setProgress(0);
		progressDialog.setTitle(title);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setMax(MAX_READPROCESS);
		progressDialog.show();
	}

	public static void showProgressDialogstyleStyle_spinner(Context cx, String title) {

		progressDialog = new ProgressDialog(cx);
		progressDialog.setProgress(0);
		progressDialog.setTitle(title);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMax(MAX_READPROCESS);
		progressDialog.show();
	}

	public static void dismissProgressDialog() {
		if (null != progressDialog) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public static void showProgressDialogWithText(Context cx, String messge) {
		progressDialog = new ProgressDialog(cx);
		progressDialog.setMessage(messge);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.show();

	}

	public static void dismissshowProgressDialogWithText() {
		if (null != progressDialog) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/*
	 * 自定义对话框 id 自定义对话框布局的id R.layout
	 */
	public static void showCustomDia(Context cx, String title, int layoutID) {
		AlertDialog.Builder customDia = new AlertDialog.Builder(cx);
		final View viewDia = LayoutInflater.from(cx).inflate(layoutID, null);
		customDia.setTitle(title);
		customDia.setView(viewDia);
		customDia.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub

			}
		});
		customDia.create().show();
	}

	// private PopupWindow window=null;
	// private View popupView;
	// /*popup window 来实现*/
	// private void showCusPopUp(View parent)
	// {
	// if(window == null)
	// {
	// popupView=LayoutInflater.from(DiaAllActivity.this).inflate(R.layout.dia_cuspopup_dia,
	// null);
	// cusPopupBtn1=(Button)popupView.findViewById(R.id.diaCusPopupSure);
	// window =new
	// PopupWindow(popupView,LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
	// }
	// window.setAnimationStyle(R.style.PopupAnimation);
	// /*必须调用setBackgroundDrawable，
	// 因为popupwindow在初始时，会检测background是否为null,如果是onTouch or onKey
	// events就不会相应，所以必须设置background*/
	// /*网上也有很多人说，弹出pop之后，不响应键盘事件了，这个其实是焦点在pop里面的view去了。*/
	// window.setFocusable(true);
	// window.setBackgroundDrawable(new BitmapDrawable());
	// window.update();
	// window.showAtLocation(parent, Gravity.CENTER_VERTICAL, 0, 0);
	// cusPopupBtn1.setOnClickListener(new OnClickListener() {
	// @Override
	// public void onClick(View v) {
	// // TODO Auto-generated method stub
	// showClickMessage("popup window的确定");
	// }
	// });
	// }
	
	//private Button cusPopupBtn1
//	private PopupWindow window=null;  
//	private void showCusPopUp(View parent)  
//    {  
//        if(window == null)  
//        {  
//            popupView=LayoutInflater.from(DiaAllActivity.this).inflate(R.layout.dia_cuspopup_dia, null);  
//            cusPopupBtn1=(Button)popupView.findViewById(R.id.diaCusPopupSure);  
//            window =new PopupWindow(popupView,LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);  
//        }  
//        window.setAnimationStyle(R.style.PopupAnimation);  
//        /*必须调用setBackgroundDrawable， 因为popupwindow在初始时，会检测background是否为null,如果是onTouch or onKey events就不会相应，所以必须设置background*/  
//        /*网上也有很多人说，弹出pop之后，不响应键盘事件了，这个其实是焦点在pop里面的view去了。*/  
//        window.setFocusable(true);  
//        window.setBackgroundDrawable(new BitmapDrawable());   
//        window.update();  
//        window.showAtLocation(parent, Gravity.CENTER_VERTICAL, 0, 0);  
//        cusPopupBtn1.setOnClickListener(new OnClickListener() {  
//            @Override  
//            public void onClick(View v) {  
//                // TODO Auto-generated method stub  
//                showClickMessage("popup window的确定");  
//            }  
//        });  
//    }  

	public static void showToast(Context cx, String message) {
		Toast.makeText(cx, message, Toast.LENGTH_SHORT).show();
	}

	public String getCurrentSystemTimeFormat() {
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		return simpleDateFormat.format(date);
	}

	public void putSharedPreferences(Context cx, String xmlName, String key, String value) {
		SharedPreferences sp = cx.getSharedPreferences(xmlName, cx.MODE_PRIVATE);// 覆盖添加，cx.MODE_APPEND追加不覆盖，MODE_WORLD_READABLE其他程序可读写MODE_WORLD_WRITEABLE其他程序可读写
		SharedPreferences.Editor editor = sp.edit();
		editor.putString(key, value);
		editor.commit();
	}

	public String getSharedPreferences(Context cx, String xmlName, String key) {
		SharedPreferences sp = cx.getSharedPreferences(xmlName, cx.MODE_PRIVATE);
		String str = sp.getString(key, "");
		return str;
	}

	public static void getDisplayMetrics(Context cx, Activity activity) {

		DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; // 屏幕宽度（像素）
		int height = metric.heightPixels; // 屏幕高度（像素）
		float density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
		int densityDpi = metric.densityDpi; // 屏幕密度DPI（120 / 160 / 240）

		DisplayMetrics dm = new DisplayMetrics();
		dm = cx.getResources().getDisplayMetrics();
		float density1 = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
		int densityDPI = dm.densityDpi; // 屏幕密度（每寸像素：120/160/240/320）
		float xdpi = dm.xdpi;
		float ydpi = dm.ydpi;

	}

	public static void installAPK(Context cx, String filePath) {
		File file = new File(filePath);
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		cx.startActivity(intent);
	}

	// 使用PM 命令安装apk
	// pm install [-l] [-r] [-t] [-i INSTALLER_PACKAGE_NAME] [-s] [-f] PATH
	// pm uninstall [-k] PACKAGE
	public static void execCommand(String... command) {
		Process process = null;
		try {
			process = new ProcessBuilder(command).start();
		} catch (IOException e) {

			e.printStackTrace();
		} finally {
			if (process != null) {
				process.destroy();
			}
		}
	}

	// execCommand("pm", "install", "-f",
	// filePath);//安装apk，filePath为apk文件路径，如/mnt/sdcard/ApiDemos.apk
	// execCommand("pm", "uninstall",
	// packageName);//卸载apk，packageName为包名，如com.example.android.apis
	// 编译生成apk时，要在你的manifest文件下添加android:sharedUserId="android.uid.system"，编译完成之后还无法正常安装，会出现Installation
	// error: INSTALL_FAILED_SHARED_USER_INCOMPATIBLE错误，此时，要为apk重新签名。

	public static void unintsllAPK(Context cx, String strPackageName) {
		Uri uri = Uri.fromParts("package", strPackageName, null);
		Intent it = new Intent(Intent.ACTION_DELETE, uri);
		cx.startActivity(it);
	}

	public static void killProcess(String packageName) {
		android.os.Process.killProcess(android.os.Process.myPid());
		// 目前获取自己的也只有该API，否则从/proc中自己的枚举其他进程吧，不过要说明的是，结束其他进程不一定有权限，不然就乱套了。

		// System.exit(0);// 常规java、c#的标准退出法，返回值为0代表正常退出

	}

	// 静默安装 文件的COPY
	// 下面3句是静默卸载系统软件命令
	// String busybox="mount -o remount rw /system";
	// String chmod="chmod 777 /system/app/HtcTwitter.apk";
	// uninstallapk="rm -r /system/app/HtcTwitter.apk";
	//
	// //下面3句是静默卸载第三方软件命令
	// String busybox1="mount -o remount rw /data";
	// String chmod1="chmod 777 /data/app/com.yingyonghui.market-2.apk";
	// uninstallapk1="pm uninstall com.yingyonghui.market";
	//
	// chmodApk(busybox1,chmod1);
	// 下面3句是静默卸载系统软件命令
	/**
	 * 对要卸载的apk赋予权限
	 */
	public void chmodApk(String busybox, String chmod) {
		try {

			Process process = null;
			DataOutputStream os = null;

			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(busybox);
			os.flush();
			os.writeBytes(chmod);
			os.flush();
			os.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/*
	 * 卸载apk
	 */
	public void uninstallApk(String uninstallapk) {
		try {

			Process process = null;
			DataOutputStream os = null;
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(uninstallapk);
			os.flush();

			os.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 在状态栏显示通知
	 * 
	 * @param title
	 *            TODO
	 * @param content
	 *            TODO
	 */
	public static void showNotification(Context cx, Class<?> cls, String title, String content) {
		// 创建一个NotificationManager的引用
		NotificationManager notificationManager = (NotificationManager) cx.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

		// 定义Notification的各种属性
		Notification notification = new Notification();
		// Notification notification = new Notification(R.drawable.ic_launcher,
		// "督导系统", System.currentTimeMillis());
		// FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉
		// FLAG_NO_CLEAR 该通知不能被状态栏的清除按钮给清除掉
		// FLAG_ONGOING_EVENT 通知放置在正在运行
		// FLAG_INSISTENT 是否一直进行，比如音乐一直播放，知道用户响应
		notification.flags |= Notification.FLAG_ONGOING_EVENT; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中
		notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在点击了通知栏中的"清除通知"后，此通知不清除，经常与FLAG_ONGOING_EVENT一起使用
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;
		// DEFAULT_ALL 使用所有默认值，比如声音，震动，闪屏等等
		// DEFAULT_LIGHTS 使用默认闪光提示
		// DEFAULT_SOUNDS 使用默认提示声音
		// DEFAULT_VIBRATE 使用默认手机震动，需加上<uses-permission
		// android:name="android.permission.VIBRATE" />权限
		notification.defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL;
		// 叠加效果常量
		// notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND;
		notification.ledARGB = Color.BLUE;
		notification.ledOnMS = 5000; // 闪光时间，毫秒

		// 设置通知的事件消息
		CharSequence contentTitle = title; // 通知栏标题
		CharSequence contentText = content; // 通知栏内容

		Intent notificationIntent = new Intent(cx, cls); // 点击该通知后要跳转的Activity
		PendingIntent contentItent = PendingIntent.getActivity(cx, 0, notificationIntent, 0);
		notification.setLatestEventInfo(cx, contentTitle, contentText, contentItent);
		// 把Notification传递给NotificationManager
		notificationManager.notify(0, notification);
	}

	// 删除通知
	public static void clearNotification(Context cx) {
		// 启动后删除之前我们定义的通知
		NotificationManager notificationManager = (NotificationManager) cx.getSystemService(cx.NOTIFICATION_SERVICE);
		notificationManager.cancel(0);
	}

	// 输入法控制
	public static void hideKeyboard(Context cx, View view) {
		InputMethodManager imm = (InputMethodManager) cx.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public static void openKeyboard(Context cx, View view) {
		InputMethodManager inputMethodManager = (InputMethodManager) cx.getSystemService(Context.INPUT_METHOD_SERVICE);
		// 接受软键盘输入的编辑文本或其它视图
		// 如果输入法打开则关闭，如果没打开则打开
		inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
	}

	public static boolean iskeyboard(Context cx, View view) {
		// isOpen若返回true，则表示输入法打开
		InputMethodManager imm = (InputMethodManager) cx.getSystemService(Context.INPUT_METHOD_SERVICE);
		boolean isOpen = imm.isActive();
		return isOpen;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 * 
	 * @param context
	 * @param dpValue
	 *            dp值
	 * @return 返回像素值
	 */
	public static int dipTopx(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 * 
	 * @param context
	 * @param pxValue
	 *            像素值
	 * @return 返回dp值
	 */
	public static int pxTodip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 短信分享
	 * 
	 * @param mContext
	 * @param smstext
	 *            短信分享内容
	 * @return
	 */
	public static Boolean sendSms(Context mContext, String smstext) {
		Uri smsToUri = Uri.parse("smsto:");
		Intent mIntent = new Intent(android.content.Intent.ACTION_SENDTO, smsToUri);
		mIntent.putExtra("sms_body", smstext);
		mContext.startActivity(mIntent);
		return null;
	}

	/**
	 * 邮件分享
	 * 
	 * @param mContext
	 * @param title
	 *            邮件的标题
	 * @param text
	 *            邮件的内容
	 * @return
	 */
	public static Boolean sendMail(Context mContext, String title, String text) {
		// 调用系统发邮件
		Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		// 设置文本格式
		emailIntent.setType("text/plain");
		// 设置对方邮件地址
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, "");
		// 设置标题内容
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, title);
		// 设置邮件文本内容
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, text);
		mContext.startActivity(Intent.createChooser(emailIntent, "Choose Email Client"));
		return null;
	}

	/**
	 * @note 获取该activity所有view
	 * @author liuh
	 * */
	public List<View> getAllChildViews(Activity activity) {
		View view = activity.getWindow().getDecorView();
		return getAllChildViews(view);
	}

	private List<View> getAllChildViews(View view) {
		List<View> allchildren = new ArrayList<View>();
		if (view instanceof ViewGroup) {
			ViewGroup vp = (ViewGroup) view;
			for (int i = 0; i < vp.getChildCount(); i++) {
				View viewchild = vp.getChildAt(i);
				allchildren.add(viewchild);
				allchildren.addAll(getAllChildViews(viewchild));
			}
		}
		return allchildren;
	}

	/**
	 * 指定PackageName包名的应用是否已安装.
	 * 
	 * @param context
	 * @param PackageName
	 * @return
	 * @throws NotFoundException
	 */
	public static boolean hasInstallApk(Context context, String PackageName) throws NotFoundException {
		boolean flag = true;
		PackageManager mPm = context.getPackageManager();
		PackageInfo pkgInfo = null;
		try {
			pkgInfo = mPm.getPackageInfo(PackageName, PackageManager.GET_UNINSTALLED_PACKAGES);
		} catch (NameNotFoundException e) {
			flag = false;
		} catch (Exception ex) {
			flag = false;
			if (pkgInfo == null) {
				throw new NotFoundException();
			}
		}
		return flag;
	}

	/**
	 * 检查系统中是否存在-这个Activity
	 * 
	 * @param context
	 * @param pkg
	 * @param cls
	 * @return
	 */
	public static boolean hasActivity(Context context, String pkg, String cls) {
		boolean has = true;
		Intent intent = new Intent();
		intent.setClassName(pkg, cls);
		if (context.getPackageManager().resolveActivity(intent, 0) == null) {
			// 说明系统中不存在这个activity
			has = false;
		}
		return has;
	}
}
